package com.example.test.util;

import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.charset.Charset;

/**
 * @Author 林文峰
 * @Date 2020/7/1 0001 15:24
 */
public class HtmlToPDF {
	private static final String PDF_PATH = "G:\\上传测试\\html2PDF.pdf";
	private static final String HTML_PATH = "F:\\下载位置\\新建文本.html";
//	private static final String CSS_PATH = "E:\\testFile\\html2pdf.css";

	public static void main(String[] args) throws Exception {
//		BaseFont baseFont = BaseFont.createFont("E:\\testFile\\msyh.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
		// 文字如果要加粗，修改第三个参数
//		Font msya = new Font(baseFont, 12, Font.NORMAL);

		Document document = new Document(PageSize.A4, 10, 10, 10, 10);//左右上下的margin
		document.setMargins(0, 0, 0, 0);
		PdfWriter pdfwriter;
		pdfwriter = PdfWriter.getInstance(document, new FileOutputStream(PDF_PATH));
		document.open();
		XMLWorkerHelper wh = XMLWorkerHelper.getInstance();
//		InputStream cssInput = new FileInputStream(CSS_PATH);
		wh.parseXHtml(pdfwriter, document, new FileInputStream(HTML_PATH));

/*		// 读取完 html 的内容后，可以继续往 pdf 文件中写其他内容
		// 读取一个图片
		Image image = Image.getInstance("E:\\testFile\\dream.jpg");
		
		image.scalePercent(50);
		image.setAlignment(Image.ALIGN_RIGHT);
		// 设置图片的绝对位置
		// image.setAbsolutePosition(0, 0);
		// image.scaleAbsolute(500, 400);
		// 插入一个图片
		document.add(image);
		document.add(new Phrase("短语标题", msya));
//		document.add(new Paragraph("\n"));
		document.add(new Paragraph("段落内容", msya));
*/
		document.close();

		System.out.println("succeed");
	}
}
